package silly;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class SillyTest {

	Connection conn;
	
	public SillyTest() {

	}
	
	public void connect() {
		try
		{
			Class.forName("com.mysql.jdbc.Driver");
		}
		catch (ClassNotFoundException e)
		{
			System.out.println("Unable to load the MySQL JDBC driver..");
			java.lang.System.exit(0); 
		}
		System.out.println("Driver loaded successfully");
		
		
		
		// creating the connection
		System.out.print("Trying to connect.. ");
		try
		{
			conn = DriverManager.getConnection(
					"jdbc:mysql://localhost:3305/DbMysql04","DbMysql04","hgkvepki");
		}
		catch (SQLException e)
		{
			System.out.println("Unable to connect - " + e.toString());
			java.lang.System.exit(0); 
		}
		System.out.println("Connected!");

	}
	
	public void closeConnection()
	{
		// closing the connection
		try
		{
			conn.close();
		}
		catch (SQLException e)
		{
			System.out.println("Unable to close the connection - " + e.toString());
			java.lang.System.exit(0); 
		}		
	}
	
	public void runQuery(String query)
	{
		Statement statement = null;
		try{
			statement = conn.createStatement();
			ResultSet rs = statement.executeQuery(query);
			System.out.println("Number of columns in result set = "+rs.getMetaData().getColumnCount());
		}
		catch (SQLException e) {
			e.printStackTrace();
		}
		finally {
			try{
				statement.close();
			}
			catch (Exception e) {
				// don't care
			}
		}
	}
	
	public void sanity()
	{
		Statement statement = null;
		try{
			statement = conn.createStatement();
			ResultSet rs = statement.executeQuery("SELECT idttt, lalala FROM ttt");
			rs.next();
			System.out.println("id = "+rs.getInt(1) + ". text = "+rs.getString(2));
		}
		catch (SQLException e) {
			e.printStackTrace();
		}
		finally {
			try{
				statement.close();
			}
			catch (Exception e) {
				// don't care
			}
		}
	}

	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		SillyTest st = new SillyTest();
		st.connect();
		System.out.println("Connected");
		st.runQuery("SELECT 1 FROM DUAL;");
		st.sanity();
		st.closeConnection();
		System.out.println("Closed");
	}

}
